from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
import requests
import random
import time
def get_color():
    color_list = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
    color = ''
    for i in range(6):
        color += color_list[random.randint(0,14)]
    return '#'+color

def elm(txt,emails):
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header

    # 第三方 SMTP 服务


    mail_host = "smtp.qq.com"  # 设置服务器
    mail_user = "bybxbwg@foxmail.com"  # 用户名
    mail_pass = "ilnnhalzojcjecfe"  # 口令

    sender = 'bybxbwg@foxmail.com'


    receivers = emails  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱

    message = MIMEText(txt, 'plain', 'utf-8')
    message['From'] = Header("宝子", 'utf-8')
    message['To'] = Header("狗子", 'utf-8')

    subject = datetime.datetime.now().__str__().split(' ')[0] + '\t贴心小提示'
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
        smtpObj.login(mail_user, mail_pass)
        print(1)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("邮件发送成功")

    except smtplib.SMTPException:
        mail_host = "smtp.madacode.com"  # 设置服务器
        mail_user = "yinhai@madacode.com"  # 用户名
        mail_pass = "20020308Yh"  # 口令
        sender = 'yinhai@madacode.com'
        receivers = ['2214372851@qq.com']
        message = MIMEText(txt, 'plain', 'utf-8')
        message['From'] = Header("我", 'utf-8')
        message['To'] = Header("我", 'utf-8')
        subject = datetime.datetime.now().__str__().split(' ')[0] + '   贴心小提示'
        message['Subject'] = Header(subject, 'utf-8')
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())


def get_email():
    # 天气
    weather = requests.get('https://www.mxnzp.com/api/weather/current/肇庆市?app_id=rgihdrm0kslojqvm&app_secret=WnhrK251TWlUUThqaVFWbG5OeGQwdz09').json()
    # 穿衣指数
    exponent = requests.get(
        'https://api.seniverse.com/v3/life/suggestion.json?key=SCYrvkytJze9qyzOh&location=zhaoqing&language=zh-Hans').json()

    # str 情话
    love = requests.get('https://api.lovelive.tools/api/SweetNothings').text
    a1 = weather['data']['address']
    a2 = weather['data']['temp']
    a3 = weather['data']['weather']
    a4 = weather['data']['humidity']
    b1 = exponent['results'][0]['suggestion']['dressing']['brief']
    b2 = exponent['results'][0]['suggestion']['flu']['brief']
    b3 = exponent['results'][0]['suggestion']['sport']['brief']
    b4 = exponent['results'][0]['suggestion']['uv']['brief']
    date = datetime.datetime.now().__str__().split(' ')[0].split('-')
    zhao = requests.get('http://api.tianapi.com/zaoan/index?key=58db52d8a478e65f7ce24a4ee3ba1d2f').json()
    zhaoan = zhao['newslist'][0]['content']
    txt = '''<!DOCTYPE html>
    <html>

    	<head>
    		<meta charset="utf-8">
    		<title>早安</title>
    	</head>

    	<body>
    		<div style="background: #F0F2F5; padding: 35px; font-size: 14px;">
    			<div style="width: 750px; margin: 0 auto; background: url('https://www.henghost.com/images/hc_email_background.png') no-repeat center; background-size: cover;">
    				<div style="padding: 0 15px; padding-bottom: 20px;">
    					<div style="height: 20px; display: flex; justify-content: space-between; position: relative;">
    					</div>
    					<div style="background: #fff; padding: 0 15px; padding-bottom: 50px;">
    						<div style="padding: 0 9px; display: flex; justify-content: space-between; align-items: center; padding-top: 10px; padding-bottom: 10px; border-bottom: 1px solid #DBDBDB;">

    						</div>
    						<img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.soogif.com%2FcDLpG1NYXusE7fNsZoUF2OTFTl4jdOnX.gif&refer=http%3A%2F%2Fimg.soogif.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1668097358&t=fa7698a377773c1b297db87b565447e3" alt="" style="width: 100%">
    						<div style="color: #41bf71; border: 1px solid #41BF71; background: #E0FFEC; padding: 14px 15px; display: flex; margin-top: 20px; margin-bottom: 30px;"><img style="width: 42px !important; height: 42px !important;" src="http://5b0988e595225.cdn.sohucs.com/images/20200314/eba9062730cc47abbfa4da9b92d08afe.gif" width="42">
    							<div style="margin-left: 14px;">
    								<div style="font-size: 16px; font-weight: bold; margin-bottom: 5px;">早上好！今天是{}年{}月{}日。</div>
    								<div style="width: 600px; line-height: 24px;">
                                    <p>{}</p>
                                    </div>
    							</div>
    						</div>
    						<div>
    							<div><span style="font-size: 16px; font-weight: bold; position: relative; top: -4px;">当天天气</span></div>
    							<table style="width: 100%; border-spacing: 0px; border-collapse: collapse; border: none; margin-top: 20px;">
    								<tbody>
    									<tr style="height: 40px; background: #F6F6F6;">
    										<th style="border: 1px solid #DBDBDB; color: #666666; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">当前城市</th>
    										<th style="border: 1px solid #DBDBDB; color: #666666; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">当前气温</th>
    										<th style="border: 1px solid #DBDBDB; color: #666666; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">天气状况</th>
    										<th style="border: 1px solid #DBDBDB; color: #666666; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">空气湿度</th>
    									</tr>
    									<tr style="height: 40px;">
    										<td style="border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">{}</td>
    										<td style="border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">{}</td>
    										<td style="border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">{}</td>
    										<td style="border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">{}</td>
    									</tr>
    								</tbody>
    							</table>
    						</div>
    						<div style="margin-top: 30px;">
    							<div><span style="font-size: 16px; font-weight: bold; position: relative; top: -4px;">穿衣指数</span></div>
    							<table style="width: 100%; border-spacing: 0px; border-collapse: collapse; border: none; margin-top: 20px;">
    								<tbody>
    									<tr style="height: 40px; background: #F6F6F6;">
    										<th style="border: 1px solid #DBDBDB; color: #666666; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">穿衣指数</th>
    										<th style="border: 1px solid #DBDBDB; color: #666666; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">感冒指数</th>
    										<th style="border: 1px solid #DBDBDB; color: #666666; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">运动指数</th>
    										<th style="border: 1px solid #DBDBDB; color: #666666; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">紫外线强度</th>
    									</tr>
    									<tr style="height: 40px;">
    										<td style="border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">{}</td>
    										<td style="border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">{}</td>
    										<td style="border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">{}</td>
    										<td style="border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">{}</td>
    									</tr>
    								</tbody>
    							</table>
    						</div>

    						<div style="margin-top: 30px;"><span style="font-size: 14px; font-weight: bold;">温馨提示</span>
    							<div style="line-height: 24px; margin-top: 10px;">
    							本页小狗专属🐶
                                <p style="color: #a346ff">{}</p>
                                <img src="http://5b0988e595225.cdn.sohucs.com/images/20200320/f1722ad7510a4b9298d1a5ef455372de.gif" alt="">
    							</div>
    						</div>
    					</div>
    				</div>
    			</div>
    		</div>
    	</body>

    </html>'''.format(
        date[0], date[1], date[2], zhaoan,
        a1, a2, a3, a4, b1, b2, b3, b4, love
    )
    elm(txt=txt, emails=["2214372851@qq.com","709308322@qq.com"])
    ##################################################

    urls = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}".format(app_id,
                                                                                                            app_secret)
    try:
        access_token = requests.get(urls).json()['access_token']
        url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={}".format(access_token)
        if len(recipients_id) > 0:
            for i in recipients_id:
                data = {
                    'touser': i,
                    'template_id': template_id,
                    "url": "http://weixin.qq.com/download",
                    'topcolor': '#FF0000',
                    'data': {
                        'date': {
                            'value': datetime.datetime.now().__str__().split(' ')[0],
                            'color': get_color()
                        },
                        'region': {
                            'value': a1,
                            'color': get_color()
                        },
                        'weather': {
                            'value': a3,
                            'color': get_color()
                        },
                        'temp': {
                            'value': a2,
                            'color': get_color()
                        },
                        'wind_dir': {
                            'value': a4,
                            'color': get_color()
                        },
                        'sunrise': {
                            'value': b1,
                            'color': get_color()
                        },
                        'sunset': {
                            'value': b2,
                            'color': get_color()
                        },
                        'pao': {
                            'value': b3,
                            'color': get_color()
                        },
                        'uv': {
                            'value': b4,
                            'color': get_color()
                        },
                        'commemoration_day1': {
                            'value': abs((datetime.datetime(year=2021, month=7, day=20)-datetime.datetime.now()).days + 1),
                            'color': get_color()
                        },
                        'zhaoan': {
                            'value': zhaoan,
                            'color': get_color()
                        },
                        'love': {
                            'value': love,
                            'color': get_color()
                        }
                    }
                }
                headers = {
                    'Content-Type': 'application/json',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                                  'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
                }
                response = requests.post(url, headers=headers, json=data).json()
                if response["errcode"] == 40037:
                    print("推送消息失败，请检查模板id是否正确")
                elif response["errcode"] == 40036:
                    print("推送消息失败，请检查模板id是否为空")
                elif response["errcode"] == 40003:
                    print("推送消息失败，请检查微信号是否正确")
                elif response["errcode"] == 0:
                    print("推送消息成功")
                else:
                    print(response)
    except KeyError:
        print('token获取失败')


if __name__ == '__main__':
    app_id = 'wx571e90fc4f76f376'
    app_secret = '430cebd96715deebd58a2c5e08791b20'
    template_id = 'ZuA4bkGPxRSXojDTL4rxkOywRTdjtFv3e8DyEsmpEVo'
    recipients_id = ['o3MpI65-IlCx067yrt4Ln39whVgk']#,'o3MpI6_TF8iUDZ7OaxtCkWqFng3I']
    # get_email()
    scheduler = BlockingScheduler()
    scheduler.add_job(get_email, 'cron', hour = 8, minute = 20)
    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass

